<template>
  <div class="pdccontent-box">
    <pdc-nav-bar @publicdynamic="publicdynamic" />
    <div class="dynamic-text">
      <van-field
        v-model="message"
        rows="2"
        autosize
        type="textarea"
        maxlength="50"
        placeholder="分享新鲜事..."
        show-word-limit
      />
    </div>
    <div class="dynamic-img">
      <van-uploader v-model="fileList" multiple :max-count="9" :after-read="afterRead" />
    </div>
  </div>
</template>

<script>
import PdcNavBar from "./pdcchildcomps/PdcNavBar";

import { getUrlBase642 } from "common/utils";
import { mapState } from "vuex";

import { publicTextDynamic } from "network/dynamic";
import { uploadingHousePicture } from "network/uploadImg";

export default {
  name: "publicdynamiccontent",
  components: {
    PdcNavBar,
  },
  data() {
    return {
      message: "",
      fileList: [],
      imageList: [],
      isCanSubmit: false,
    };
  },
  methods: {
    toBack() {
      this.$router.back();
    },
    //发表动态
    publicdynamic() {
      if (this.isCanSubmit) {
        this.$toast({
          message: "图片正在上传中~",
          position: "bottom",
        });
        return;
      }
      let userId = this.userId;
      let context = this.message;
      let imageList = this.imageList;
      if (!context) {
        this.$toast({
          message: "发表内容不能为空",
          position: "bottom",
        });
        return;
      }
      publicTextDynamic({ userId, context, imageList }).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.$toast({
            message: "发布成功",
            position: "bottom",
          });
          this.$router.replace("/friendcircle");
          this.message = "";
          this.fileList = [];
          this.imageList = [];
        }
      });
    },
    //上传图片
    afterRead(file) {
      if (file.length > 1) {
        //使用for循环来适配多选情况
        for (let i in file) {
          this.upimg(file[i]);
        }
      } else {
        this.upimg(file);
      }
    },
    //上传图片到服务器
    upimg(file) {
      this.isCanSubmit = true;
      file.status = "uploading";
      file.message = "上传中...";
      // 大于1MB的图片都缩小像素上传
      if (file.file.size > 1048576) {
        let canvas = document.createElement("canvas"); // 创建Canvas对象(画布)
        let context = canvas.getContext("2d");
        let img = new Image();
        img.src = file.content; // 指定图片的DataURL(图片的base64编码数据)
        img.onload = () => {
          canvas.width = 400;
          canvas.height = 300;
          context.drawImage(img, 0, 0, 400, 300);
          file.content = canvas.toDataURL(file.file.type, 0.92); // 0.92为默认压缩质量
          let files = this.dataURLtoFile(file.content, file.file.name);
          const data = new FormData();
          data.append("files", files);
          uploadingHousePicture(data)
            .then((res) => {
              console.log("123", res);
              if (res.code == 200) {
                this.isCanSubmit = false;
                this.imageList.push(res.data[0]);
                file.status = "";
                file.message = "";
              }
            })
            .catch(() => {
              this.isCanSubmit = false;
              this.$toast({
                message: "上传失败",
                position: "bottom",
              });
              file.status = "failed";
              file.message = "上传失败";
            });
        };
      } else {
        //小于1M直接上传
        const data = new FormData();
        data.append("files", file.file);
        uploadingHousePicture(data)
          .then((res) => {
            console.log(res);
            if (res.code == 200) {
              this.isCanSubmit = false;
              this.imageList.push(res.data[0]);
              file.status = "";
              file.message = "";
            }
          })
          .catch(() => {
            this.isCanSubmit = false;
            this.$toast({
              message: "上传失败",
              position: "bottom",
            });
            file.status = "failed";
            file.message = "上传失败";
          });
      }
    },
    dataURLtoFile(dataurl, filename) {
      // 将base64转换为file文件
      let arr = dataurl.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
  },
  computed: {
    ...mapState({
      userId: (state) => state.moduleUser.userId,
    }),
  },
};
</script>

<style scoped>
.pdccontent-box {
  padding-top: 50px;
  height: 100vh;
  background-color: #efefef;
}
.dynamic-text {
  margin: 15px;
  border-radius: 10px;
  overflow: hidden;
}
.dynamic-img {
  margin: 15px;
  border-radius: 10px;
  padding: 15px 30px;
  background-color: #fff;
}
</style>